<template>
  <div class="user-page">
    <div class="toolbar">
      <el-input
        v-model.number="filters.userId"
        placeholder="筛选用户ID"
        clearable
        style="width: 180px; margin-right: 10px"
      />
      <el-input
        v-model="filters.email"
        placeholder="模糊搜索邮箱"
        clearable
        style="width: 240px; margin-right: 10px"
      />
      <!-- 返回按钮 -->
      <el-button type="primary" @click="goBack"> 返回 </el-button>
      <el-button type="primary" @click="openAddDialog">新增用户</el-button>
    </div>

    <el-table :data="users" border style="width: 100%; background-color: white">
      <el-table-column prop="userId" label="用户ID" />
      <el-table-column prop="userName" label="用户名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="userSystemRole" label="用户系统角色" />
      <el-table-column prop="passWord" label="密码" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="openEditDialog(row)"
            >编辑</el-button
          >
          <el-button size="small" type="danger" @click="deleteUser(row.userId)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑/新增弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户' : '新增用户'"
    >
      <el-form :model="formData" label-width="80px">
        <!-- 编辑时显示 userId，新增时不显示 -->
        <el-form-item v-if="isEdit" label="用户ID">
          <el-input v-model.number="formData.userId" disabled />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="formData.userName" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="formData.email" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="formData.userSystemRole"
            placeholder="请选择角色"
            style="width: 180px"
          >
            <el-option label="学生" value="student" />
            <el-option label="老师" value="teacher" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="formData.passWord" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getUsers,
  addUser,
  updateUser,
  deleteUser as apiDeleteUser,
} from "../api/user.js";
import { useRouter } from "vue-router";

const router = useRouter();

const goBack = () => {
  router.back(); // 返回上一级页面
  // 或者跳转到首页： router.push("/api/redirect");
};

const filters = ref({ userId: "", email: "" });
const users = ref([]);

const dialogVisible = ref(false);
const isEdit = ref(false);

const formData = ref({
  userId: null,
  userName: "",
  email: "",
  passWord: "",
});

// 加载用户数据
const loadUsers = async () => {
  try {
    const res = await getUsers({
      userId: filters.value.userId,
      email: filters.value.email,
    });
    users.value = res?.data || [];
  } catch (error) {
    ElMessage.error("加载用户失败");
  }
};

onMounted(loadUsers);

const openAddDialog = () => {
  isEdit.value = false;
  formData.value = {
    userName: "",
    email: "",
    passWord: "",
  };
  dialogVisible.value = true;
};

const openEditDialog = (user) => {
  isEdit.value = true;
  formData.value = { ...user };
  dialogVisible.value = true;
};

const saveUser = async () => {
  const { userId, userName, email, passWord } = formData.value;

  if (!userName || !email || !passWord || (isEdit.value && !userId)) {
    ElMessage.warning("所有字段不能为空");
    return;
  }

  try {
    if (isEdit.value) {
      await updateUser(formData.value);
      ElMessage.success("更新成功");
    } else {
      await addUser(formData.value);
      ElMessage.success("添加成功");
    }
    dialogVisible.value = false;
    await loadUsers();
  } catch (error) {
    ElMessage.error("保存失败");
  }
};

const deleteUser = async (userId) => {
  ElMessageBox.confirm("确认删除该用户吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      await apiDeleteUser(userId);
      ElMessage.success("删除成功");
      await loadUsers();
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};
</script>

<style scoped>
.user-page {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(
      rgba(255, 255, 255, 0.8),
      rgba(255, 255, 255, 0.8)
    ),
    url("../assets/gao.png") center/cover no-repeat;
  background-attachment: fixed;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
